<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>鼠标画多边形</title>
  <style>
    #canvas {
      border: 1px solid #000;
    }
  </style>
</head>
<body>

<canvas id="canvas" width="400" height="300"></canvas>

<script>
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');

  var points = [];
  var closeDistance = 10;  // 定义吸附距离

  // 加载图片
  var image = new Image();
  image.src = 'https://webstatic.mihoyo.com/upload/op-public/2023/05/30/ac698e2d5ea0f66317d189d7697a5d04_1233201386636480873.png';  // 替换为您的图片路径
  image.onload = function() {
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
  };

  canvas.addEventListener('click', function(e) {
    var rect = canvas.getBoundingClientRect();
    var x = e.clientX - rect.left;
    var y = e.clientY - rect.top;

    // 如果是最后一个点，并且有一点与第一个点相同，结束绘制
    if (points.length > 1 && isCloseToFirstPoint(x, y)) {
      drawLines(points[points.length - 1].x, points[points.length - 1].y, points[0].x, points[0].y);
      points = [];  // 清空点数组
    } else {
      points.push({ x, y });
      drawPoint(x, y);

      if (points.length > 1) {
        var prevPoint = points[points.length - 2];
        drawLines(prevPoint.x, prevPoint.y, x, y);
      }
    }
  });

  function isCloseToFirstPoint(x, y) {
    // 判断当前点是否接近第一个点
    var firstPoint = points[0];
    var distance = Math.sqrt(Math.pow(x - firstPoint.x, 2) + Math.pow(y - firstPoint.y, 2));
    return distance < closeDistance;
  }

  function drawPoint(x, y) {
    ctx.beginPath();
    ctx.arc(x, y, 3, 0, 2 * Math.PI);
    ctx.fillStyle = 'red';
    ctx.fill();
  }

  function drawLines(x1, y1, x2, y2) {
    // 绘制线段
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
  }
</script>

</body>
</html>
